package org.example.config;

/**
 * @Description TokenParseFilter
 * @Author xiaotian
 * @Date 2025-04-04
 */
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.example.common.utils.JwtUtils;
import org.example.common.utils.ThreadLocalUtil;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class TokenParseFilter extends PathMatchingFilter {

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);

        // 获取请求 URI
        String requestURI = httpRequest.getRequestURI();

        // 如果路径包含 "api" 或 "wxApi"，解析 Token
        if ( requestURI.contains("/wxApi")) {
            // 从 Header 或参数中获取 Token
            String token = httpRequest.getHeader("token");
            if (token == null || token.isEmpty()) {
                token = httpRequest.getParameter("token");
            }

            // 解析 Token 并获取用户信息
            if (token != null && !token.isEmpty()) {
                try {
                    String userId = JwtUtils.parseJWT(token).getSubject();
                    if (userId != null && !userId.isEmpty()) {
                        ThreadLocalUtil.setUserId(userId); // 存储用户信息
                    }
                } catch (Exception e) {
                    // Token 解析失败，可以选择记录日志或忽略
                    System.out.println("Token 解析失败: " + e.getMessage());
                }
            }
        }

        // 继续执行后续逻辑
        return true;
    }
}